/**
 * Created by huachuan on 2016/1/3.
 */
angular.module('meetingcontrollers',[])
  //发现的首页（约局）的Controller
 .controller('DiscoverIndexCtrl',function($scope,$rootScope,$ionicSlideBoxDelegate,$cordovaStatusbar,$ionicPopup,$cordovaFileTransfer,$ionicActionSheet,$ionicScrollDelegate,$timeout,$state,Calendar,LBS,Loading,Meeting,MsgBox,MeAttend,Home,ENV,Storage,Toast,ShareService,ShareServiceOther){
    /************顶部日历*************/
    $scope.weekDay = [];
    var selectedDay = new Date();
    var lookTime = '';
   $scope.nowDate = new Date();

    //点击顶部的日期进行选择
    $scope.selectDay = function(timestr){
      $ionicScrollDelegate.scrollTop();
      $scope.nowDate = selectedDay =new Date(timestr);
      for(i=0;i<$scope.weekDay.length;i++){
        if(timestr==$scope.weekDay[i].timeformat){
          $scope.weekDay[i].selected = true;
        }else{
          $scope.weekDay[i].selected = false;
        }
      }
      //根据具体时间获取活动
      Meeting.getActivityByDay(memberId,timestr);
      lookTime = timestr;
      Loading.showLoading();
    }
/*    //向左滑动
    $scope.swipeRight = function(){
      $ionicScrollDelegate.scrollTop();
      $scope.isShowMeeting = true;
    }
    //向右滑动
    $scope.swipeLeft = function(){
      $ionicScrollDelegate.scrollTop();
      if(firstInHome){
        firstInHome = false;
        Loading.showLoading();
      }
      $scope.isShowMeeting = false;
      Home.getHomeList(memberId);
    }*/
    //点击前一周
    $scope.preWeek = function(dayStr){
      $ionicScrollDelegate.scrollTop();
     var curDate =  new Date(dayStr);
      var preDate = new Date(curDate.getTime() - 24*60*60*1000);  //前一天
      $scope.nowDate = lookTime = selectedDay = preDate;//保存当前获取的时间
      var weekDay =  getWeekDay(preDate);
      Calendar.getCalendar(weekDay,'indexActivity',memberId);
      Meeting.getActivityByDay(memberId,formatDate(preDate));
    }
    //点击下一周
    $scope.nextWeek = function(dayStr){
      $ionicScrollDelegate.scrollTop();
      var curDate =  new Date(dayStr);
      var nextDate = new Date(curDate.getTime() + 24*60*60*1000);  //后一天
      $scope.nowDate= lookTime =selectedDay = nextDate;
      var weekDay =  getWeekDay(nextDate);
      Calendar.getCalendar(weekDay,'indexActivity',memberId);
      Meeting.getActivityByDay(memberId,formatDate(nextDate));
    }

  /*******************顶部日期结束******************/
    //回到顶部
    $rootScope.backToTop = function(){
      $ionicScrollDelegate.scrollTop(true);
    }
    /*******************************定位功能开始*********************************/
    $scope.$on('LBS.locationSuccess',function(){
      var location = LBS.getLocation();
      var point = new BMap.Point(location.longitude,location.latitude);
      var gc = new BMap.Geocoder();
      gc.getLocation(point, function (rs) {
        var addComp = rs.addressComponents;
        var city  = addComp.city;
        LBS.setLocationCityName(city);//定位的城市
        LBS.getCityByName(city);
      });
    });
    $scope.$on('LBS.getCityJsonUpdated',function(){
      var locationCity = LBS.getCityJson();
      Storage.set('lbsCity',locationCity);
      $scope.city = locationCity.ciity_name;
    });
    $scope.go2Lbs = function(){
      $state.go('lbs');
    }
    /********************************定位功能结束********************************/
    //打开应用后首次在发现页面
    var firstInApp = true;
    //获取会员编号
    var memberId = '';
    $scope.picPath = ENV.picPath;
    var releaseMark = '';
    //进入页面时,获取消息盒子的数量
    $scope.$on('ShareService.QQInstalled', function () {
      $scope.isShareShow = ShareService.getIsShowShareWindow();
    });
    $scope.$on('ShareService.WeiBoInstalled', function () {
      $scope.isShareShow = ShareService.getIsShowShareWindow();
    });
    $scope.$on('ShareService.WeixinInstalled', function () {
      $scope.isShareShow = ShareService.getIsShowShareWindow();
    });
  $scope.$on('$ionicView.beforeEnter',function(){
    //检测第三方登录平台
    document.addEventListener("deviceready", function () {
      ShareService.checkQqIsInstalled();
      ShareService.checkWechatIsInstalled();
      ShareService.checkWeiBoIsInstalled();
    }, false);
    memberId = Storage.get("member").member_id;
    $scope.addIsActive = false;
    $rootScope.showWineGlasses = false;
    if($scope.isShowMeeting){
      if(lookTime!=''){
        Meeting.getActivityByDay(memberId,lookTime);
      }else{
        Meeting.getActivityByDay(memberId);
      }
    }else{
      Home.getHomeList(memberId);
    }
    $scope.city = Storage.get('lbsCity');
    MsgBox.getMsgBoxCount(memberId);
    if(Home.haveNewRelease()){
      var home = Home.getReleaseHomeJson();
      Home.setNewRelease(false);
      if(home.mark=='onlyContent'){//不带图片的
        $scope.homeList.unshift(home);
      }else{
        for(i=0;i<$scope.homeList.length;i++){//带图片的
          if($scope.homeList[i].mark == home.mark){
            $scope.homeList[i] = home;
          }
        }
      }
    }
    //判断是否有新发布的酒窝信息（带图片的）
    if(Home.getIsUploadingReleaseHome()) {
      var result = Home.getNewReleaseHome();
      releaseMark = result.mark;
      result.homeMemberInfo = $scope.member;
      $scope.homeList.unshift(result);
    }
    //获取到周日历
    if($scope.isShowMeeting) {
      var weekDay2 = getWeekDay(selectedDay);
      if(firstInApp){
        $scope.weekDay = weekDay2;
      }
      Calendar.getCalendar(weekDay2,'indexActivity',memberId);
    }
    //当页面不是第一次进入的时候，重新加载酒窝的点赞状态，收藏状态，评论数
    if($scope.homeList!=undefined && $scope.homeList.length!=0&&!$scope.isShowMeeting){
        searchList = [];
        for(i=0;i<$scope.homeList.length;i++){
          if(!$scope.homeList[i].isLocal){
            search = {
              mh_id:$scope.homeList[i].mh_id,
              member_id:memberId,
              look_member_id:$scope.homeList[i].homeMemberInfo.member_id
            }
            searchList.push(search);
          }
        }
      Home.getCurrentHomeInfo(searchList);//获取
    }
    //当页面在约局这一边的时候，获取约局的点赞状态，收藏状态，评论数
    if($scope.isShowMeeting && $scope.meetingList!=undefined && $scope.meetingList.length>0){
      searchList = [];
      for(i=0;i<$scope.meetingList.length;i++){
        search = {
          mm_id:$scope.meetingList[i].mm_id,
          member_id:memberId
        }
        searchList.push(search);
      }
        if(searchList.length>0){
          Meeting.getCurrentMeetingInfo(searchList);
        }
    }
  //使用定位功能
    if(firstInApp){
      LBS.getPosition();
      firstInApp = false;
    }
  });
    $scope.$on('Meeting.getCurrentMeetingInfoUpdated',function(){
      var result = Meeting.getCurrentInfo();
      for(i=0;i<$scope.meetingList.length;i++){
        for(j=0;j<result.length;j++){
          if($scope.meetingList[i].mm_id==result[j].mm_id){
            $scope.meetingList[i].mm_comment_num = result[j].mm_comment_num;
            $scope.meetingList[i].lmeetStatus = result[j].lmeetStatus;
            $scope.meetingList[i].mcmeetStatus = result[j].mcmeetStatus;
          }
        }
      }
    });
    //获取到处理过的日历
    $scope.$on('Calendar.getCalendarUpdated',function(){
      $scope.weekDay = Calendar.getWeekDayJson();
    });
    $scope.$on('MsgBox.msgBoxCountUpdated',function(){
      var result = MsgBox.getMsgBoxCountJson();
      $scope.msgBoxCount = result.msgBoxCount;
    });
    $scope.$on('Meeting.activityUpdated', function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.meetingList = Meeting.getActivityListJson().meetingList;
    });

    /******对四个小图标的处理*****/
    var collectIndex = '';//收藏的索引
    var likeIndex = '';//点赞的索引

    //显示约局分享框
    $scope.showMeetingShare = function(mm_id){
      ShareServiceOther.showShareWindow(mm_id,"meeting");
    };

    //显示酒窝分享框
    $scope.showHomeShare = function(mh_id){
      ShareServiceOther.showShareWindow(mh_id,"home");
    };
    //收藏
    $scope.collectMeeting = function(index,mmId){
      Loading.showLoading();
      collectIndex = index;
      Meeting.collectMeeting(memberId,mmId);
    };
    //网络访问成功后
    $scope.$on('Meeting.collectMeetingUpdated', function(){
      Loading.hideLoading();
      var result = Meeting.getCollectJson();
      $scope.meetingList[collectIndex].mcmeetStatus = result.mcmeetStatus;
      Toast.showMessage(result.mcmeetMsg);
      collectIndex='';
    });
    //点赞
    $scope.likeMeeting = function(index,mmId){
      Loading.showLoading();
      likeIndex = index;
      Meeting.likeMeeting(memberId,mmId);
    };
    //网络访问成功后
    $scope.$on('Meeting.likeMeetingUpdated', function(){
      Loading.hideLoading();
      var result = Meeting.getLikeJson();
      $scope.meetingList[likeIndex].lmeetStatus = result.lmeetStatus;
      Toast.showMessage(result.lmeetMsg);
      likeIndex='';
    });
    //评论
    $scope.commentMeeting = function(index){
      var mmName = $scope.meetingList[index].mm_title;
      var mmId = $scope.meetingList[index].mm_id;
      Storage.set('mmName',mmName);
      Storage.set('mmId',mmId);
      $state.go('meetingComment');
    };
    /**************************************以下为酒窝的内容********************************/
    //显示酒杯或者隐藏酒杯

    $rootScope.goToWineIndex = function(){
      $rootScope.showWineGlasses = true;
      $scope.addIsActive = true;
      $timeout(function(){
        $state.go('productIndex');
      },300);
    }
    $scope.release = function(){
      $timeout(function(){
        if($scope.isShowMeeting){
          $state.go('release-date');
        }else{
          $state.go('release-home');
        }
      },300);
      $rootScope.showWineGlasses = true;
      $scope.addIsActive = true;
      }

   /* $scope.slideChanged = function(index){
      if(index==0){
        showMeetingFun();
      }else if(index==1){
        showHomeFun();
        Home.getHomeList(memberId);
      }
    }*/



    $scope.isShowMeeting = true;
    $scope.showMeeting = function(){
      //$ionicSlideBoxDelegate.slide(0,300);
      showMeetingFun();
    }
    $scope.showHome = function(){
     // $ionicSlideBoxDelegate.slide(1,300);
      showHomeFun();
    }
    $scope.swipeLeft = function(){
      showHomeFun();
    }
    $scope.swipeRight = function(){
      showMeetingFun();
    }
    showMeetingFun = function(){
     // $ionicScrollDelegate.scrollTop();
      $scope.isShowMeeting = true;
      $scope.addIsActive = false;
      $rootScope.showWineGlasses = false;
    }
    var firstInHome = true;
    showHomeFun = function(){
     // $ionicScrollDelegate.scrollTop();
      $scope.addIsActive = false;
      $rootScope.showWineGlasses = false;
      if(firstInHome){
        firstInHome = false;
        Loading.showLoading();
        Home.getHomeList(memberId);
      }
      $scope.isShowMeeting = false;
    }
    //下拉刷新
    $scope.doRefreshMeeting = function(){
      Meeting.getActivityByDay(memberId,formatDate(selectedDay));
    }
    $scope.doRefreshHome = function(){
      console.log("doRefreshHome");
      Home.getHomeList(memberId);
    }

    //加载更多
    $scope.loadMore = function(){
        Home.getMoreHomeList(memberId);
    }
    //是否有下一页
    $scope.hasNextPage = function() {
      return Home.hasNextPage();
    };
    $scope.$on('Home.homeListResponseUpdated',function(){
        Loading.hideLoading();
        $scope.$broadcast('scroll.refreshComplete');
        //延时两秒显示加载图标
        $timeout(function(){
          $scope.$broadcast('scroll.infiniteScrollComplete');
        },2000);
        $scope.member = Home.getHomeMemberInfo();
        //获取到酒窝的信息
        $scope.homeList = Home.getHomeListJson().data;

        if(Home.getIsUploadingReleaseHome()) {
          var result = Home.getNewReleaseHome();
          releaseMark = result.mark;
          result.homeMemberInfo = $scope.member;
          $scope.homeList.unshift(result);
      }
    });

    //发布带有图片的酒窝的时候调用
    $scope.$on('Home.releaseHomePicUpdated',function(){
      Home.setNewRelease(false);//接收到广播
      Home.setUploadingReleaseHome(false);
      Home.saveNewReleaseHome('');
      var result = Home.getReleaseHomeJson();
      if(result.releaseHomeState){
        if(result.mark==releaseMark){
          for(var i=0;i<$scope.homeList.length;i++){
            if($scope.homeList[i].mark == result.mark){
              $scope.homeList[i] = result;
              break;
            }
          }
        }
      }else{
        Toast.showMessage(result.releaseHomeMsg);
      }
    });
    $scope.showBigImage= function(homeIndex,picIndex){
      var items = [];
      var pswpElement = document.querySelectorAll('.pswp')[0];
      var lookImageList = $scope.homeList[homeIndex].picSrc;
      if($scope.homeList[homeIndex].isLocal){//本地图片
        for(i=0;i<lookImageList.length;i++){
          var imgWH =  getNaturalWidth(lookImageList[i]);
          var temp01 = {
            src:lookImageList[i],
            w:imgWH[0],
            h:imgWH[1]
          };
          items.push(temp01);
        }
      }else{
        for(i=0;i<lookImageList.length;i++){//网络图片
          var temp02 = {
            src:$scope.picPath+"big_"+lookImageList[i].src,
            w:lookImageList[i].w,
            h:lookImageList[i].h
          };
          items.push(temp02);
        }
      }
      var options = {
        index: picIndex,
        history: false,
        focus: false,
        loop: false,
      /*  pinchToClose:false,
        closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true,
        loadingIndicatorDelay:100
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
      console.log($rootScope.gallery);
    // $cordovaStatusbar.hide();

    }
    //长按下载
    $rootScope.downloadHomeImg = function(){
      var url = $rootScope.gallery.currItem.src;
      var timestamp=new Date().getTime();
      var targetPath = cordova.file.externalRootDirectory+"winelife/winelife_home_"+timestamp+".jpg";
      var trustHosts = true;
      var options = {};
      $ionicActionSheet.show({
        buttons: [
          {text: '保存到手机相册'}
        ],
        cancelText: '取消',
        buttonClicked: function (index) {
          if(index==0){
            $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
              .then(function(result) {
                Toast.showMessage("保存成功");
              }, function(err) {
                Toast.showMessage("保存成功");
              }, function (progress) {
              });
          }
          return true;
        }
      });
    }
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
     // $cordovaStatusbar.show();
    }
    //收藏酒窝
    var collectorLikeHomeIndex = '';
    $scope.collectHome =function(index,mhId){
        Home.collectHome(memberId,mhId);
        collectorLikeHomeIndex = index;
    }
    $scope.$on('Home.collectHomeUpdated',function(){
      Loading.hideLoading();
      var result = Home.getCollectHomeMsgJson();
      Toast.showMessage(result.mchomeMsg);
      $scope.homeList[collectorLikeHomeIndex].mchomeStatus = result.mchomeStatus;
    });
    //点赞酒窝
    $scope.likeHome =function(index,mhId){
        Home.likeHome(memberId,mhId);
        collectorLikeHomeIndex = index;
    }
    $scope.$on('Home.likeHomeUpdated',function(){
      Loading.hideLoading();
      var result = Home.getLikeHomeMsgJson();
      Toast.showMessage(result.lhomeMsg);
      $scope.homeList[collectorLikeHomeIndex].lhomeStatus = result.lhomeStatus;
    });

    //关注会员
    var focusIndex = '';
    $scope.foucsMember = function(toAttendMemberId,index){
      MeAttend.focusFriend(memberId,toAttendMemberId);
      focusIndex = index;
    }
   // var saveNoAttendMemberId = '';
    $scope.noFoucsMember = function(toAttendMemberId,index){

      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要取消关注吗？</p>',
        cancelText: '继续关注',
        okText: '取消关注',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          //删除对应的酒窝
          Loading.showLoading();
          MeAttend.focusFriend(memberId,toAttendMemberId);
        }
      });
    }
    //关注或者取消关注时访问网络成功返回的信息
    $scope.$on('MeAttend.focusFriendUpdated',function(){
      Loading.hideLoading();
      var result = MeAttend.getFocusFriendMsgJson();
      if(result.isAttendMsg!='网络异常，请稍后再试'){
          //$scope.homeList[focusIndex].isAttend = result.isAttend;
        for(i=0;i<$scope.homeList.length;i++){
          if($scope.homeList[i].homeMemberInfo.member_id==result.attend_member_id){
            $scope.homeList[i].isAttend = result.isAttend;
          }
        }
      }
      Toast.showMessage(result.isAttendMsg);
    });

    //点击用户头像是的操作
    $scope.go2OtherHome  = function(otherMemberId){
      if(memberId==otherMemberId){
        $state.transitionTo("tab.meIndex");
      }else{
        $state.transitionTo("user-dimple-care-list",{memberId:otherMemberId});
      }
    }
    //删除酒窝
    $scope.showDeleteHome = false;
    var saveHomeIndex = '';
    $scope.deleteHome = function(homeIndex){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要删除该酒窝吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          //删除对应的酒窝
          Loading.showLoading();
          //$scope.homeList[saveHomeIndex].mh_id 酒窝的编号
          Home.deleteHome(memberId,$scope.homeList[homeIndex].mh_id);
          saveHomeIndex = homeIndex;
        }
      });
    }
    $scope.$on('Home.deleteHomeUpdated',function(){
      Loading.hideLoading();
      var result = Home.getDeleteHomeMsgJson();
      if(result.deleteHomeState){
          $scope.homeList.splice(saveHomeIndex,1);
      }
      Toast.showMessage(result.deleteHomeMsg);
      //Loading.hideLoading();
    });

    $scope.$on('Home.currentHomeInfoeUpdated',function(){
      var result = Home.getCurrentJson().currentInfo;
      for(i=0;i<result.length;i++){
          for(j=0;j<$scope.homeList.length;j++){
            if(result[i].mh_id==$scope.homeList[j].mh_id){
              $scope.homeList[j].isAttend  = result[i].isAttend;
              $scope.homeList[j].lhomeStatus = result[i].lhomeStatus;
              $scope.homeList[j].mchomeStatus = result[i].mchomeStatus;
              $scope.homeList[j].mh_comment_num = result[i].mh_comment_num;
              $scope.homeList[j].mh_praise_num = result[i].mh_praise_num;
            }
          }
      }
    });


  })






  //酒窝评论的Controller
  .controller('HomeCommentCtrl',function($scope,$state,$stateParams,$ionicPopup,Loading,HomeComment,History,ENV,Storage,Toast){

    $scope.picPath = ENV.picPath;
    var mhId = $stateParams['mhId'];
    var memberId = '';
    var isFirstIn = true;
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get('member').member_id;
      if(isFirstIn){
        Loading.showLoading();
        isFirstIn = false;
      }
      //获取评论列表
      HomeComment.getCommentList(mhId,memberId);
    });


    $scope.commentList = [];
    $scope.memberInfo={
      member_img_url:'',
      mr_img_url:''
    };
    //新增评论
    $scope.comment={
      newComment:''
    };
    //删除评论
    var deleteIndex = '';
    $scope.deleteComment = function(mhcId,index){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要删除该评论吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          Loading.showLoading();
          HomeComment.deleteComment(mhcId,memberId,mhId);
          deleteIndex = index;
        }
      });
    }
    $scope.$on('HomeComment.deleteCommentUpdated',function(){
      Loading.hideLoading();
      var result = HomeComment.getDelCommentJson();
      if(result.dmCommentStatus){
        $scope.commentList.splice(deleteIndex,1);
      }
      Toast.showMessage(result.dmCommentMsg);
    });

    $scope.$on('Home.CommentListUpdated',function(){
      Loading.hideLoading();
      $scope.commentList=HomeComment.getCommentJson().commentList;
      $scope.memberInfo.member_img_url =HomeComment.getCommentJson().memberInfo.member_img_url;
    });
    //发表评论
    $scope.publishComment = function(){
      if($scope.comment.newComment ==''){
        Toast.showMessage("评论的内容不能为空");
      }else{
        Loading.showLoading();
        HomeComment.publishComment(mhId,memberId,$scope.comment.newComment);
        $scope.comment.newComment = '';//使得输入框中的值为空
      }
    };
    //请求网络数据完成之后
    $scope.$on('Home.publishCommentUpdated', function() {
      Loading.hideLoading();
      var newComment = HomeComment.getNewComment();
      if(newComment.amCommentStatus){
        $scope.commentList.unshift(newComment);
      }
      Toast.showMessage(newComment.amCommentMsg);
    });
    //返回
    $scope.goback = function(){
      History.goback();
    }
  });



